<template>
  <div>
    <h1>与 AI 聊天</h1>
    <textarea v-model="userMessage" placeholder="请输入您的问题..."></textarea>
    <button @click="sendMessage">发送</button>

    <div v-if="aiReply">
      <h3>AI 回复：</h3>
      <p>{{ aiReply }}</p>
    </div>

    <div v-if="error" class="error">
      <p>请求失败，请稍后再试！</p>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import axios from "axios";

// 数据绑定
const userMessage = ref("");
const aiReply = ref<string | null>(null);
const error = ref<boolean>(false);

// 发送消息给后端
const sendMessage = async () => {
  try {
    error.value = false; // 清除错误提示
    const response = await axios.post("/api/ai/chat", userMessage.value);
    // 提取 AI 回复内容
    aiReply.value = response.data.choices[0]?.message?.content || "没有回复";
  } catch (err) {
    console.error(err);
    error.value = true; // 显示错误提示
  }
};
</script>

<style scoped>
/* 简单样式 */
textarea {
  width: 100%;
  height: 100px;
  margin-bottom: 10px;
}
button {
  padding: 10px 20px;
  color: white;
  cursor: pointer;
  background-color: #007bff;
  border: none;
}
button:hover {
  background-color: #0056b3;
}
.error {
  font-weight: bold;
  color: red;
}
</style>
